package cn.itcast.bookstore.user.web.servlet;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.bookstore.cart.domain.Cart;
import cn.itcast.bookstore.user.domain.User;
import cn.itcast.bookstore.user.service.UserException;
import cn.itcast.bookstore.user.service.UserService;
import cn.itcast.commons.CommonUtils;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;
import cn.itcast.servlet.BaseServlet;

/**
 * User表述层
 */
public class UserServlet extends BaseServlet {

	private UserService userService = new UserService();
	
/**
 * 退出功能
 */
	public String quit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		request.getSession().invalidate();
		return "f:/index.jsp";
	}
	
	
	
	
	
	/**
	 * 登录功能
	 */
	public String login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		/*
		 *1.封装表单数据到form中
		 *2.输入校验（略）
		 *3.调用service完成激活
		 *	》保存错误信息、form到request，转发到login.jsp
		 *4.保存信息到session中，然后重定向到index.jsp 
		 */
		User form  = CommonUtils.toBean(request.getParameterMap(), User.class);
		try{
			User user = userService.login(form);
			request.getSession().setAttribute("session_user", user);
			//////////////////////////////////////////////////////////
			
			//给用户添加一个购物车，即向session中保存一个cart对象
			request.getSession().setAttribute("cart", new Cart());
			
			////////////////////////////////////////////////////////////
			return "r:/index.jsp";
		}catch(UserException e){
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("form", form);
			return "f:/jsps/user/login.jsp";
		}
		
	}
	
	
	/**
	 * 激活功能
	 */
	public String active(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		/*
		 *1.获取参数激活码
		 *2.调用service方法完成激活
		 *	》保存异常信息到request域
		 *3. 保存成功信息到request域，转发到msg.jsp
		 */
		System.out.println("恭喜您，成功激活！");
		String code = request.getParameter("code");
		request.setAttribute("msg", "恭喜，您激活成功，请登录！");
		try{
			userService.active(code);
		}catch(UserException e){
			request.setAttribute("msg", e.getMessage());
		}
		return "f:/jsps/msg.jsp";
	}
	
/**
 * 注册功能
 */
	public String regist(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 1.封装表单数据到form对象中
		 * 2.补全：uid，code
		 * 3.输入校验
		 * 		》保存错误信息、form到regist域，转发到regist.jsp
		 * 4.调用service方法完成注册
		 * 		》保存错误信息、form到regist域，转发到regist.jsp
		 * 5.发邮件
		 * 6.保存成功信息到msg.jsp
		 */
		//封装表单数据
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		//补全
		form.setUid(CommonUtils.uuid());
		form.setCode(CommonUtils.uuid()+CommonUtils.uuid());
		/*
		 * 输入校验
		 * 	1.创建一个Map，用来封装表单数据，其中key为表单字段名称，值为错误信息
		 */
		Map<String,String> errors = new HashMap<String, String>();
		/*
		 * 2.获取form中的username、password、email进行校验
		 */
		String username = form.getUsername();
		if(username == null || username.trim().isEmpty()){
			errors.put("username", "用户名不能为空！");
		}else if(username.length() < 3 || username.length() > 10){
			errors.put("username", "用户名长度必须在3~10个字符之间");
		}
		
		String password = form.getPassword();
		if(password ==  null || password.trim().isEmpty()){
			errors.put("password", "密码不能为空！");
		}else if(password.length() < 3 || password.length() > 10){
			errors.put("password", "密码长度需在3~10个字符之间，请重新设置！");
		}
		
		/*String email = form.getEmail();
		if(email == null || email.trim().isEmpty()){
			errors.put("email", "邮箱不能为空！");
		}else if(!email.matches("\\w+@\\w+\\.\\w+")){
			errors.put("email", "eamil邮箱格式错误，请重新输入！");
		}*/
		
		
		String email = form.getEmail();
		if(email == null || email.trim().isEmpty()){
			errors.put("email", "邮箱不能为空！");
		}else if(!email.matches("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$")){
			errors.put("email", "eamil邮箱格式错误，请重新输入！");
		}
		/*
		 *3.判断是否存在错误信息 
		 */	
		if(errors.size()>0){
			//1.保存错误信息
			//2.保存表单数据
			//3.转发到regist.jsp
			request.setAttribute("errors", errors);
			request.setAttribute("form", form);
			return"f:/jsps/user/regist.jsp";
		}
		/*
		 *调用service的regist方法 
		 */
		try {
			userService.regist(form);
			
		} catch (UserException e) {
			/*
			 * 1.保存异常信息
			 * 2.保存form
			 * 3.转发到fegist.jsp
			 */
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("form", form);
			return "f:/jsps/user/regist.jsp";
		}

		/*
		 *发邮件 
		 *1.准备配置文件
		 */
		//获取配置文件内容
		Properties pros = new Properties();
		pros.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
		
		String host = pros.getProperty("host");
		String uname = pros.getProperty("uname");
		String pwd = pros.getProperty("pwd");
		String from = pros.getProperty("from");
		String to = form.getEmail();
		String subject = pros.getProperty("subject");
		String content = pros.getProperty("content");
		content = MessageFormat.format(content, form.getCode());//替换{0}
		
		Session session = MailUtils.createSession(host, uname, pwd);//得到session
		Mail mail = new Mail(from,to,subject,content);//创建邮件对象
		try {
			MailUtils.send(session, mail);//发邮件
		} catch (MessagingException e) {
			e.printStackTrace();
		}
			
		
		
		
		/*
		 * 执行到这里，如果userService执行成功，没有抛出异常
		 * 1.保存成功信息
		 * 2.转发到msg.jsp
		 */
		request.setAttribute("msg", "恭喜，注册成功！请马上到邮箱激活！");
		String s = getServletContext().getRealPath("/");
		System.out.println(s);
		return "f:/jsps/msg.jsp";
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}
